﻿using Dapper;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace DAL
{
    public class UserRoleDal
    {
        private string URL;
        public UserRoleDal()
        {
            dynamic jsonObject = JsonConvert.DeserializeObject(File.ReadAllText("appsettings.json"));
            URL = jsonObject.ConnectionStrings.SqlServer;
        }

        public async Task<List<Users>> FindAllUserInfo()
        {
            using (SqlConnection con = new SqlConnection(URL))
            {
                string sql = "select * from sys_users";
                return (await con.QueryAsync<Users>(sql)).ToList();
            }
        }

        //登录
        public async Task<UserRole> LoginAsync(string u_name, string u_password)
        {
            using (SqlConnection con = new SqlConnection(URL))
            {
                string sql = $"select * from user_role_view where users_name='{u_name}' and users_password='{u_password}'";
                UserRoleView roleView = await con.QueryFirstOrDefaultAsync<UserRoleView>(sql);
                if (roleView != null)
                {
                    return new UserRole
                    {
                        Id = roleView.UsersId,
                        Name = roleView.UsersName,
                        TrueName = roleView.UsersTrueName,
                        RolesName = roleView.RolesName,
                        OrgId = roleView.OrgId
                    };
                }
                else
                {
                    return new UserRole
                    {
                        Id = 0,
                        Name = "",
                        TrueName = "",
                        RolesName = "",
                        OrgId = 0
                    };
                }
            }
        }
    }
}
